import QtQuick 2.0
import QtSensors 5.0 as Sensors
import "QUItMeterComponent"

Rectangle {
    id: root

    //Generate dummy values when testing without accelerometer (e.g. PC)
    property bool feedWithDummyValues: false

    width: 1200
    height: 800
    color: "#000000"

    QUItMeterComponent {
        id: meter
        width: parent.width
        height: parent.height/2
        ledWidth: ledWidthSlider.value
        ledHeight: ledHeightSlider.value
        updateFrequency: meterSpeedSlider.value
        SequentialAnimation on value {
            running: root.feedWithDummyValues
            loops: Animation.Infinite
            NumberAnimation { from: 0.5; to: 1; duration: 300; easing.type: Easing.InOutQuad }
            NumberAnimation { from: 1.0; to: 0.5; duration: 1000; easing.type: Easing.OutElastic }
            NumberAnimation { from: 0.5; to: 0.2; duration: 2000; easing.type: Easing.InOutElastic }
        }
    }

    Sensors.Accelerometer {
        id: accel
        dataRate: 100
        active: !root.feedWithDummyValues
        onReadingChanged: {
            var v = Math.sqrt(accel.reading.x * accel.reading.x + accel.reading.y * accel.reading.y + accel.reading.z * accel.reading.z);
            // Max 3G force
            v = v / (3*9.81);
            meter.value = v;
        }
    }

    // Add mirror effect
    ShaderEffect {
        property variant source: ShaderEffectSource { sourceItem: meter; hideSource: false }

        anchors.top: meter.bottom
        width: meter.width
        height: meter.height

        fragmentShader: "
            varying highp vec2 qt_TexCoord0;
            uniform highp float qt_Opacity;
            uniform sampler2D source;
            void main(void) {
                highp vec2 pos = vec2(qt_TexCoord0.x, (1.0 - qt_TexCoord0.y*0.8));
                pos.x += (qt_TexCoord0.y*0.2) * (pos.x * -1.0 + 1.0);
                highp vec4 pix = texture2D(source, pos);
                pix *= (0.4 - qt_TexCoord0.y*0.5) * min(qt_TexCoord0.y*5.0, 1.0);
                gl_FragColor = pix * qt_Opacity;
            }"
    }

    Row {
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 40
        width: parent.width
        spacing: 0
        property int elementWidth: width/3 - spacing
        Slider {
            id: ledWidthSlider
            width: parent.elementWidth
            caption: "Led width: " + value + " px"
            minimum: 8
            maximum: 128
            value: 32
        }
        Slider {
            id: ledHeightSlider
            width: parent.elementWidth
            caption: "Led height: " + value + " px"
            minimum: 8
            maximum: 64
            value: 16
        }
        Slider {
            id: meterSpeedSlider
            width: parent.elementWidth
            caption: "Meter speed: " + (60/value).toFixed(2) + " fps"
            minimum: 1
            maximum: 20
            value: 5
        }
    }
}
